//
//  OrderSureFirstVC.m
//  CenturyCity
//
//  Created by beisheng03 on 2018/1/10.
//  Copyright © 2018年 beisheng. All rights reserved.
//

#import "OrderSureFirstVC.h"
#import "OrderSelectPayCell.h"
#import "OrderTotalPriceCell.h"
#import "OrderMessageCell.h"
#import "OrderSendMethdCell.h"
#import "OrderGoddsListCell.h"
#import "OrderHaveAdressCell.h"
#import "OrderNoAdressCell.h"
#import "KeepCallSectionHeader.h"

#import "KeepCallBottomView.h"
#import "AdressMangerVC.h"
#import "WineCategoryVC.h"
#import <WXApi.h>
#import <AlipaySDK/AlipaySDK.h>

@interface OrderSureFirstVC ()
/** <#note#> */


@property (nonatomic, strong) KeepCallBottomView *footerView;

@end

@implementation OrderSureFirstVC



- (KeepCallBottomView *)footerView{
    
    if (!_footerView) {
      
        KeepCallBottomView *temp = (KeepCallBottomView *)[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([KeepCallBottomView class]) owner:nil options:nil].firstObject;
        
        temp.backgroundColor = viewBgGrey;
        
        [temp.topBtn setTitle:@"确认支付" forState:UIControlStateNormal];
        [temp.topBtn setTitle:@"确认支付" forState:UIControlStateHighlighted];
        
        [temp.topBtn addTarget:self action:@selector(gotoPay) forControlEvents:UIControlEventTouchUpInside];
        
        temp.frame = CGRectMake(0, 0, KScreenW,72);
        
        _footerView = temp;
        
        [self.view addSubview:temp];
        
    }
    
    return _footerView;
}


/**
 * 提交订单（实物商品）
 * uid             *  会员id
 * coupon_id          使用的优惠劵id
 * goods_sku_list  *  商品列表  9:2,11:3(sku_id:num)规则:规则数量
 * leavemessage       会员留言
 * mobile             收货人电话         不传使用会员默认收货地址
 * province           收货地址省 id      不传使用会员默认收货地址
 * city               收货地址市 id      不传使用会员默认收货地址
 * district           收货地址县区 id    不传使用会员默认收货地址
 * address            收货地址详情       不传使用会员默认收货地址
 */

- (void)gotoPay{
    
    if (self.dataModel.selectAdress == nil) {
        
        [SVProgressHUD showWithStatus:@"请选择收货地址!"];
        
        return;
    }
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"goods_sku_list"] = self.goodsListStr;
    parameters[@"uid"] = myViewModel.user.uid;
    parameters[@"mobile"] = self.dataModel.selectAdress.mobile;
    parameters[@"province"] = self.dataModel.selectAdress.province;
    parameters[@"city"] = self.dataModel.selectAdress.city;
    parameters[@"district"] = self.dataModel.selectAdress.district;
    parameters[@"address"] = self.dataModel.selectAdress.address;
//    NSLog(@"%@-------",self.dataModel.leavemessage);
    if (self.dataModel.leavemessage.length > 0) {
        parameters[@"leavemessage"] = self.dataModel.leavemessage;
    }
    
    [SVProgressHUD showWithStatus:@"订单确认中..."];
   
    MJWeakSelf;
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:GET_METHOD URLPath:@"Order/orderCreate" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        
        if (!error) {
            
            
            [weakSelf lastPayWitPayment:responseObject[@"data"][@"pay_rmb"] outTradeNo:responseObject[@"data"][@"out_trade_no"]];
            
            if ([weakSelf.clearShopCar isEqualToString:@"NO"]) {
                
            } else {
                [weakSelf clearShoCar];

            }
            
            
          
            
        } else {
            
          
            [SVProgressHUD showInfoWithStatus:error.domain];
        }
    }];
    
    
  
    
  
}



- (void)clearShoCar{
    
    
    
//    for (GoodsSetionModel *sectionModel in myViewModel.shopCar.shopCarList) {
//
//        for (GoodsSkuListModel *sub in sectionModel.goods) {
//
//            if ([sub.isSelect isEqualToString:@"1"]) {
//                 [setionModel.goods removeObjectAtIndex:index.row];
//
//            }
//
//
//
//        }
//    }
    
    [myViewModel.shopCar.shopCarList removeAllObjects];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"didClearShopCar" object:nil];
    
    [myViewModel.shopCar saveUserInfo];
    
    
    
//    GoodsSetionModel *setionModel = myShopCar.shopCarList[index.section];
//
//
//
//    if (setionModel.goods.count < 1) {
//
//        [myShopCar.shopCarList removeObjectAtIndex:index.section];
//
//    }
    
}



//http://feidu.baonongkang.cn/index.php/api/




- (void)lastPayWitPayment:(NSString *)payment outTradeNo:(NSString *)trade{
    //    ?out_trade_no=&pay_type=2&payment=0.01
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"payment"] = payment;
    parameters[@"out_trade_no"] = trade;

    if ([self.dataModel.alipay isEqualToString:@"1"]) {
        
        parameters[@"pay_type"] = @"2";
        
        [self AlipayPayWith:parameters];

    } else {
        
        parameters[@"pay_type"] = @"1";
        
        [self wachatPay:parameters];


    }
    
    
}


- (void)AlipayPayWith:(NSMutableDictionary *)parameters{
    
    
    
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"Pay/pay_order" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        
        if (!error) {
            
            [SVProgressHUD dismiss];
            
            [[AlipaySDK defaultService] payOrder:responseObject[@"data"] fromScheme:@"com.beisheng.feifubao" callback:^(NSDictionary *resultDic) {
                
                
                NSLog(@"reslut = %@",resultDic);
                
            }];
            
            
        } else {
            
            [SVProgressHUD showInfoWithStatus:error.domain];
            
        }
        
        
    }];
    
    
    
}

- (void)wachatPay:(NSMutableDictionary *)parameters{
    
    
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"Pay/pay_order" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        
        if (!error) {
            
            [SVProgressHUD dismiss];
            
            MYJSONSTR;
            
            [self WXPayWithDic:responseObject[@"data"]];

            
        } else {
            
            
            [SVProgressHUD showInfoWithStatus:error.domain];
            
        }
        
        
    }];
    
    
    

    
    
    
}



- (void)WXPayWithDic:(NSDictionary *)dic{
    
    //需要创建这个支付对象
    PayReq *req   = [[PayReq alloc] init];
    //由用户微信号和AppID组成的唯一标识，用于校验微信用户
    req.openID = dic[@"appid"];
    
    // 商家id，在注册的时候给的
    req.partnerId = dic[@"partnerid"];
    
    // 预支付订单这个是后台跟微信服务器交互后，微信服务器传给你们服务器的，你们服务器再传给你
    req.prepayId  = dic[@"prepayid"];
    
    // 根据财付通文档填写的数据和签名
    //这个比较特殊，是固定的，只能是即req.package = Sign=WXPay
    req.package   = dic[@"pkg"];
    
    // 随机编码，为了防止重复的，在后台生成
    req.nonceStr  = dic[@"noncestr"];
    
    // 这个是时间戳，也是在后台生成的，为了验证支付的
    NSString * stamp = dic[@"timestamp"];
    
    req.timeStamp = stamp.intValue;
    
    // 这个签名也是后台做的
    req.sign = dic[@"sign"];
    
    //发送请求到微信，等待微信返回onResp
    [WXApi sendReq:req];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"确认订单";
    
    self.tableView.backgroundColor = viewBgGrey;
    
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.tableView.estimatedRowHeight = 100;
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderSelectPayCell class]) bundle:nil] forCellReuseIdentifier:[OrderSelectPayCell identifierStr]];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderTotalPriceCell class]) bundle:nil] forCellReuseIdentifier:[OrderTotalPriceCell identifierStr]];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderMessageCell class]) bundle:nil] forCellReuseIdentifier:[OrderMessageCell identifierStr]];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderSendMethdCell class]) bundle:nil] forCellReuseIdentifier:[OrderSendMethdCell identifierStr]];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderGoddsListCell class]) bundle:nil] forCellReuseIdentifier:[OrderGoddsListCell identifierStr]];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderHaveAdressCell class]) bundle:nil] forCellReuseIdentifier:[OrderHaveAdressCell identifierStr]];
  
     [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderNoAdressCell class]) bundle:nil] forCellReuseIdentifier:[OrderNoAdressCell identifierStr]];
    
    
      [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([KeepCallSectionHeader class]) bundle:nil] forHeaderFooterViewReuseIdentifier:[KeepCallSectionHeader identifierStr]];
    
    MJWeakSelf
    self.tableView.mj_header = [XMGRefreshHeader headerWithRefreshingBlock:^{
        
        [weakSelf loadData];
        
    }];
    
    [weakSelf.tableView.mj_header beginRefreshing];
    
    
    self.footerView.hidden = YES;
    
    self.tableView.tableFooterView = self.footerView;
    
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(WXApiDidSuccessNotification) name:WXApiDidSuccessNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(WXApiDidFailNotification) name:WXApiDidFailNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(AlipayDidSuccessNotification) name:AlipayDidSuccessNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(AlipayDidFailNotification) name:AlipayDidFailNotification object:nil];
    
}



- (void)WXApiDidSuccessNotification{
    
    WineCategoryVC *temp = [[WineCategoryVC alloc]init];
    
    temp.type = @"allOrder";
    
    temp.seletIndex = 2;
    
    [self.navigationController pushViewController:temp animated:YES];
    
}

- (void)WXApiDidFailNotification{
    
    WineCategoryVC *temp = [[WineCategoryVC alloc]init];
    
    temp.type = @"allOrder";
    
    temp.seletIndex = 1;
    
    [self.navigationController pushViewController:temp animated:YES];
    
}

- (void)AlipayDidSuccessNotification{
    
    WineCategoryVC *temp = [[WineCategoryVC alloc]init];
    
    temp.type = @"allOrder";
    
    temp.seletIndex = 2;
    
    [self.navigationController pushViewController:temp animated:YES];
    
}


- (void)AlipayDidFailNotification{
    
    WineCategoryVC *temp = [[WineCategoryVC alloc]init];
    
    temp.type = @"allOrder";
    
    temp.seletIndex = 1;
    
    [self.navigationController pushViewController:temp animated:YES];
    
}


- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}





- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    
}



//http://feidu.baonongkang.cn/index.php/api/

- (void)loadData{

    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"sku_list"] = self.goodsListStr;
    parameters[@"uid"] = myViewModel.user.uid;
  
    
    MJWeakSelf;
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:GET_METHOD URLPath:@"Order/orderInfo" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        if (!error) {
            
//                        MYJSONSTR
            //            _model.lastString
            
//                       [responseObject[@"data"]  propertyCode];
            
  
            
             weakSelf.dataModel = [OrderSureModel mj_objectWithKeyValues:responseObject[@"data"]];
            
//            [weakSelf.dataModel.addresslist removeAllObjects];
            
            if (weakSelf.dataModel.addresslist.count > 0) {
                for (AddressInfoModel *sub in weakSelf.dataModel.addresslist) {
                    if ([sub.is_default isEqualToString:@"1"]) {
                        weakSelf.dataModel.selectAdress = sub;
                    }
                }
            }
            
            

            
            weakSelf.footerView.hidden = NO;
            
            weakSelf.dataModel.alipay = @"1";

            
            [weakSelf.tableView.mj_header endRefreshing];
            
            
            
            [weakSelf.tableView reloadData];
            
            
        } else {
            
            [weakSelf.tableView.mj_header endRefreshing];
            
            [SVProgressHUD showInfoWithStatus:error.domain];
            
        }
    }];
    
    
    
    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (self.dataModel == nil) {
        return 0;
    } else {
        return 3;
    }
    
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    if (self.dataModel == 0) {
        
        return 0;
        
    } else {
        if (section == 0) {
            return 1;
        } else if (section == 1) {
            
            return self.dataModel.list.count + 3;
        }else{
            
            return 2;
        }
    }
    
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        if (self.dataModel.selectAdress) {
            
            OrderHaveAdressCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[OrderHaveAdressCell identifierStr]];
            
            tableCell.model = self.dataModel.selectAdress;
            
            return tableCell;
        } else {
            OrderNoAdressCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[OrderNoAdressCell identifierStr]];
            
            return tableCell;
        }
        
 
        
    } else if (indexPath.section == 1){
        
        if (indexPath.row == self.dataModel.list.count + 2) {
            
            OrderTotalPriceCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[OrderTotalPriceCell identifierStr]];
            
            tableCell.model = self.dataModel;
            
            
            return tableCell;
            
        } else if (indexPath.row == self.dataModel.list.count + 1){
            
            OrderMessageCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[OrderMessageCell identifierStr]];
            
            tableCell.tableView = self.tableView;
            
            tableCell.model = self.dataModel;
            
            return tableCell;
            
        }else if (indexPath.row == self.dataModel.list.count){
            
            OrderSendMethdCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[OrderSendMethdCell identifierStr]];
            
            
            return tableCell;
            
        }else{
            
            OrderGoddsListCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[OrderGoddsListCell identifierStr]];
            
            
            tableCell.model =  self.dataModel.list[indexPath.row];
            
            return tableCell;
            
        }
        
  
        
    }else{
        
        OrderSelectPayCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[OrderSelectPayCell identifierStr]];
        
        tableCell.index = indexPath;
        
        
        tableCell.model = self.dataModel;
        
        return tableCell;
        
        
    }
    
    
   
}




- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 2) {
        return 44;
      
    } else {
        
        if (section == 0) {
            return 0.00001;
        } else {
            return 10;
        }
        
        
    }
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    
    return 0.00001;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section == 2) {
        
        KeepCallSectionHeader *view = (KeepCallSectionHeader *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:[KeepCallSectionHeader identifierStr]];
        
        return view;
        
        
    } else {
        
        UIView *temp = [[UIView alloc]init];
        
        temp.backgroundColor = viewBgGrey;
        
        return temp;

    }
    
    
    
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    
    UIView *temp = [[UIView alloc]init];
    
    temp.backgroundColor = [UIColor whiteColor];
    
    return temp;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        AdressMangerVC *adressVC = [[AdressMangerVC alloc]init];
        
        adressVC.vc = self;
        
        [self.navigationController pushViewController:adressVC animated:YES];
    }
    
  
        
        if (indexPath.section == 2) {
            
            if (indexPath.row == 0) {
                
                if ([self.dataModel.alipay isEqualToString:@"1"]) {
                    
                    return;
                    
                } else {
                    
                    self.dataModel.alipay = @"1";
                    self.dataModel.wechatPay = @"0";
                    
                }
                
                
            } else {
                
                if ([self.dataModel.wechatPay isEqualToString:@"1"]) {
                    
                    return;
                    
                } else {
                    
                    self.dataModel.wechatPay = @"1";
                    self.dataModel.alipay = @"0";
                    
                }
                
                
            }
            
            [self.tableView reloadData];
            
        }
    
    
    
    
}


- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    
    [self.view endEditing:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
